//
//  NetService.m
//  Ruique
//
//  Created by xiute on 2018/10/28.
//  Copyright © 2018 cuijin. All rights reserved.
//

#import "NetService.h"
#import <AFNetworking.h>

@interface NetService ()

@property (nonatomic, strong) AFHTTPSessionManager *afManager;

@end

@implementation NetService

+ (instancetype)shareInstance {
    static NetService *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[NetService alloc]init];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        self.afManager = [[AFHTTPSessionManager alloc]initWithBaseURL:[NSURL URLWithString:@"https://pastebin.com"]];
        AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
        AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
        self.afManager.requestSerializer = requestSerializer;
        self.afManager.responseSerializer = responseSerializer;
    }
    return self;
}

- (NSURLSessionDataTask *)getUrl:(NSString *)url
                           param:(id __nullable)param
                        Complete:(CompleteResponse)complet {
    return [self.afManager GET:url parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self handleSuccessData:responseObject complete:complet task:task];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (complet) {
            complet(NO, error, task, nil);
        }
    }];
}

- (void)handleSuccessData:(id)response complete:(CompleteResponse)complete task:(NSURLSessionDataTask *)task{
    if (![response isKindOfClass:[NSData class]]) {
        NSError *error = [NSError errorWithDomain:NSNetServicesErrorDomain code:10001 userInfo:@{@"description": @"服务返回的数据有些问题"}];
        if (complete) {
            complete(NO, error, task, nil);
        }
        return;
    }
    NSString *jsonStr = [[NSString alloc]initWithData:response encoding:NSUTF8StringEncoding];
    NSLog(@"%@", jsonStr);
    NSError *jsonError;
    NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:&jsonError];
    if (jsonError) {
        if (complete) {
            complete(NO, jsonError, task, nil);
        }
        return;
    }
    if (complete) {
        complete(YES, nil, task, jsonDic);
    }
    
    
}

@end
